package com.xyz.rok.tools.controller;

import com.xyz.rok.tools.constant.SystemCode;
import com.xyz.rok.tools.exception.DKPException;
import com.xyz.rok.tools.exception.TitleException;
import com.xyz.rok.tools.exception.UnionException;
import com.xyz.rok.tools.exception.UserException;
import com.xyz.rok.tools.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result handler(Exception e) {
        log.error("exception:{}", e.getMessage(), e);
        if (e instanceof MethodArgumentNotValidException) {
            StringBuilder builder = new StringBuilder();
            BindingResult result = ((MethodArgumentNotValidException) e).getBindingResult();
            if (result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                errors.forEach(p -> {
                    FieldError fieldError = (FieldError) p;
                    builder.append(fieldError.getDefaultMessage());
                });
            }
            return Result.error(SystemCode.SYS_ARG_NOT_VALID.getCode(), builder.toString());
        } else if (e instanceof UnionException) {
            UnionException unionException = (UnionException) e;
            return Result.error(unionException.getSystemCode());
        } else if (e instanceof UserException) {
            UserException userException = (UserException) e;
            return Result.error(userException.getSystemCode());
        } else if (e instanceof TitleException) {
            TitleException titleException = (TitleException) e;
            return Result.error(titleException.getSystemCode());
        } else if (e instanceof DKPException) {
            DKPException dkpException = (DKPException) e;
            return Result.error(dkpException.getSystemCode());
        } else {//其他未捕获异常
            return Result.error(SystemCode.SYS_ERROR.getCode(), SystemCode.SYS_ERROR.getMessage());
        }
    }

}
